import React from 'react';
import { connect } from 'dva';
import {Upload, Modal,Icon,message,Button} from 'antd'
import docCookies from "../../common/DocCookies";

export default class UploadFile extends React.Component {

  state = {
    preview: "",
    visible: false,
    fileList: [],
    addedFileList:[],
    uploadToken: {},
    isShowUploadButton:true,
    defaultList:[]
  }

  componentWillReceiveProps (newProps){
    const { defaultList,maxFileCount } = newProps;
    if(defaultList.length != 0) {
      var cCount = 0;
      for (var i in defaultList) {
        if (defaultList[i].status === 'done') {
          var _b = false;
          if (this.state.defaultList.length === 0) {
            _b = true;
          } else {
            for (var j in this.state.defaultList) {
              if (this.state.defaultList[j].url === defaultList[i].url) {
                _b = false;
                break;
              } else {
                _b = true;
              }
            }
          }

          if (_b) {
            this.state.defaultList.push(defaultList[i]);
            this.state.addedFileList.push(defaultList[i].url);
            cCount++;
          }
        }
      }
      if (cCount >= maxFileCount) {
        this.state.isShowUploadButton = false;
      }
      this.setState({
        defaultList: defaultList,
        addedFileList: this.state.addedFileList,
        isShowUploadButton: this.state.isShowUploadButton
      });
      // if(defaultList.length != 0){
      //   var cCount = 0;
      //   for(var i in defaultList){
      //     if(defaultList[i].status == 'done') {
      //       this.state.defaultList.push(defaultList[i]);
      //       this.state.addedFileList.push(defaultList[i].url);
      //       cCount++;
      //     }
      //   }
      //   if(cCount >= maxFileCount){
      //     this.state.isShowUploadButton=false;
      //   }
      //
      //   this.setState({
      //     defaultList:defaultList,
      //     addedFileList:this.state.addedFileList,
      //     isShowUploadButton:this.state.isShowUploadButton
      //   });
      // }
    }
  }

  beforeUpload = file => {
    const { suffixDefault } = this.props;
    var fileName = file.name;
    var suffix = fileName.substr(fileName.lastIndexOf('.')+1);

    var isVaild = false;
    for(var i in suffixDefault){
      if(suffix.toLowerCase().endsWith(suffixDefault[i])){
        isVaild = true;
        break;
      }
    }
    if(!isVaild){
      message.error("上传文件类型错误，只允许上传"+suffixDefault.join(",")+"类型的文件")
    }
    return isVaild;
  }

  handlePreview = (file) => {
    this.setState({
      preview: file.url || file.thumbUrl,
      visible: true,
    });
  }

  handleFileListChange = (info) => {
    let file = info.file;

    if(file.status == "done"){
      let fileList = info.fileList;

      message.success(file.response.msg);
      if(this.props.maxFileCount <= fileList.length) {
        this.state.isShowUploadButton = false;
      }else {
        this.state.isShowUploadButton = true;
      }
      this.state.addedFileList.push(file.response.data.upUrl);
      this.setState({
        fileList:fileList,
        isShowUploadButton:this.state.isShowUploadButton,
        addedFileList:this.state.addedFileList
      });
    }
    if(file.status != "uploading") {
      this.props.getImgSrc(this.state.addedFileList);
    }else{
      this.setState({
        isShowUploadButton:false
      });
    }
  }

  handleCancel = () => this.setState({ visible: false })

  render() {
    const {preview, visible, fileList,isShowUploadButton,defaultList,addedFileList} = this.state;
    const {data,acceptName,buttonName} = this.props;

    let listType = 'picture-card';

    if(acceptName != 'image/*'){
      listType = 'text';
    }

    const props = {
      onRemove: (file) => {
        const index = fileList.indexOf(file);
        const newFileList = fileList.slice();
        newFileList.splice(index, 1);
        defaultList.splice(index, 1);
        addedFileList.splice(index, 1);
        this.setState({
          fileList:newFileList,
          isShowUploadButton:true,
          addedFileList:addedFileList
        });
      },
      onChange:this.handleFileListChange,
      beforeUpload: this.beforeUpload,
      onPreview: this.handlePreview,
      accept: acceptName,
      listType: listType,
      name:"file",
      action:"/api/oss/fileUpload",
      data: data,
      headers:{
        'Authorization':'Bearer '+docCookies.getItem("token"),
      }
    };
    const uploadPicButton = (<div>
         <Icon type="plus"/>
          <div className="ant-upload-text">{buttonName?buttonName:'头像上传'}</div>
        </div>
    );
    const uploadButton = (
        <Button>
          <Icon type="upload" /> {buttonName?buttonName:'头像上传'}
        </Button>
  );

    return(
      <div>
        <Upload {...props} defaultFileList={defaultList}>
          {
            isShowUploadButton ? (listType == 'text'?uploadButton:uploadPicButton) : null
          }
        </Upload>
        <Modal visible={visible} footer={null} onCancel={this.handleCancel}>
          <img alt="example" style={{ width: '100%' }} src={preview} />
        </Modal>
      </div>
    )
  }

}
